<template>

        <Card style="min-height:550px;background:#fff;padding-bottom:16px;padding-top:20px">
            <!--搜索条件-->
            <Select v-model="type" style="width:20%;margin-left:15px" v-if="recordType!=2" @on-change="getData(1)">
                <Option v-for="item in list1" :value="item.type" :key="item.type">{{ item.name }}</Option>
            </Select>

            <Select v-model="rechargeType" style="width:20%;margin-left:15px" v-if="recordType==2" @on-change="getData(1)">
                <Option v-for="item in list3" :value="item.recharge" :key="item.recharge">{{ item.name }}</Option>
            </Select>

            <Select v-model="time" style="width:20%;margin-left:10px" @on-change="getData(1,true)">
                <Option v-for="item in list2" :value="item.time" :key="item.time">{{ item.name }}</Option>
            </Select>

            <DatePicker 
            v-show="time==3"
            :transfer="true" 
            placement="bottom" 
            type="daterange" 
            placeholder="选择时间段" 
            style="width:20%;margin-left:10px"
            :clearable="false"
            v-model="timeRange"></DatePicker>

            <Button style="margin-left:10px" type="primary" icon="ios-search" @click="getData(1)">搜索</Button>			
            <Button style="margin-left:10px" type="primary" @click="getCurrentElemeter" :loading="isRefreshElemeterData" v-if="recordType==0">获取最新电量</Button>
            <Button style="margin-left:10px" type="primary" @click="getCurrentWatermeter" v-if="recordType==1">获取最新用水</Button>			
            <Button style="margin-left:10px" type="primary" @click="exportTable">导出报表</Button>			
            <!--搜索条件end-->			
            <br>
            <br>
            <div v-if="recordType == 0" class="margin-bottom-10 margin-left-20">{{usageStatistics}}</div>
            <!--表格数据-->
            <Table stripe border 
            :columns="columns[recordType]" 
            :data="recordType !==2 ? datas.slice( (currentPage-1) *size, currentPage*size ) : datas"
            size="small" :loading="isLoadig"></Table>
            <!--表格数据end-->

            <!--分页-->
            <Page :total="total" 
            :page-size="size" 
            show-elevator 
            v-if="recordType==2"
            @on-change="getData"
            show-total style="text-align:center"></Page>
            <!--分页end-->

            <!--用电记录无分页，前端分页-->
            <Page :total="total" 
            :page-size="size" 
            :current.sync="currentPage"
            show-elevator 
            v-if="recordType !==2"
            show-total style="text-align:center"></Page>
            <!--用电记录无分页，前端分页end-->
            </Card>	

</template>	

<script>
import isNumber from 'lodash/isNumber'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import dayjs from 'dayjs'
import { RoomTypeEnum, ElemeterPayMode } from '@/libs/const'
const now = dayjs().endOf('day').valueOf()
const timeBefore3 = dayjs().add(-3, 'days').startOf('day').valueOf()
const timeBefore7 = dayjs().add(-7, 'days').startOf('day').valueOf()
const timeBefore30 = dayjs().add(-30, 'days').startOf('day').valueOf()
export default {
  name: 'abnormal_report',
  props: {
    recordType: {
      // recordType: 0 电表记录;  1 水表记录;   2 充值记录
      default: 1,
      required: true
    },
    roomId: {
      required: true
    },
    homePoolSetting: [Object, Boolean] // 房源公摊设置(用电设置需要)
  },
  computed: {
    // 分租的公区或关闭公摊 不显示公摊信息
    shouldNotShowPool () {
      return (this.roomInfo && this.roomInfo.room_type === RoomTypeEnum.PUBLIC) || this.homePoolSetting === false
    },

    usageStatistics () {
      if (!this.datas) return ''
      const [ roomUsage, poolUsage ] = this.datas
        .reduce(([ roomUsage, poolUsage ], { room_consume, pool_consume }) => {
          if (typeof room_consume === 'number') roomUsage += room_consume
          if (typeof pool_consume === 'number') poolUsage += pool_consume
          return [ roomUsage, poolUsage ]
        }, [ 0, 0 ])
      const totallyUsage = (this.shouldNotShowPool ? roomUsage : roomUsage + poolUsage).toFixed(2)
      const usageDetail = this.shouldNotShowPool ? '' : `, 其中房间用电: ${roomUsage.toFixed(2)}度, 公摊用电: ${poolUsage.toFixed(2)}度`
      return `总用电: ${totallyUsage}度` + usageDetail
    },

    isPayFirst () {
      return this.roomInfo && this.roomInfo.pay_type && this.roomInfo.pay_type === ElemeterPayMode.PREPAID
    }
  },
  data () {
    let columns1 = []
    let columns2 = [
      {
        title: '时间',
        align: 'center',
        // key: 'time',
        render: (createElement, obj) => {
          return createElement(
            'span', // 标签名称
            dayjs(Number(obj.row.time)).format(this.type === 'day' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm')
          )
        }
      },
      {
        title: '热水用量（吨）',
        align: 'center',
        key: 'hot',
        render (createElement, obj) {
          let hot_records = obj.row.hot_records
          let result = hot_records == null || hot_records === undefined ? '-' : Math.round(hot_records * 100) / 100
          return createElement('span', result)
        }
      },
      {
        title: '冷水用量（吨）',
        align: 'center',
        key: 'cold',
        render (createElement, obj) {
          let cold_records = obj.row.cold_records
          let result = cold_records == null || cold_records === undefined ? '-' : Math.round(cold_records * 100) / 100
          return createElement('span', result)
        }
      }
    ]
    let columns3 = [
      {
        align: 'center',
        title: '时间',
        minWidth: 160,
        // key: 'time',
        render: (createElement, obj) => {
          return createElement(
            'span', // 标签名称
            new Date(obj.row.charge_time).Format('yyyy-MM-dd HH:mm:ss')
          )
        }
      },
      {
        align: 'center',
        title: '渠道',
        minWidth: 100,
        render (createElement, obj) {
          let channelMap = ['人工充值', '微信', '支付宝', '接口充值']
          return createElement(
            'span', // 标签名称
            channelMap[obj.row.charge_channel - 1] || '-'
          )
        }
      },
      {
        align: 'center',
        title: '充值人',
        minWidth: 100,
        render: (h, { row }) => {
          const { charge_name, charge_channel } = row
          const tag = ['[员工]', '[租客]', '[租客]', 'system'][(charge_channel || 1) - 1]
          return <span>{tag} {charge_channel === 4 ? '' : charge_name}</span>
        }
      },
      {
        align: 'center',
        title: '金额（元）',
        minWidth: 120,
        render: (h, { row }) => {
          const { ele_price, fees } = row
          if (ele_price === null) return (<span>-</span>)
          return (
            <span>{(Number(fees) / 100 || 0).toFixed(4)}</span>
          )
        }
      },
      {
        align: 'center',
        title: '电价（元/度）',
        minWidth: 130,
        render: (h, { row }) => {
          const { ele_price } = row
          if (ele_price === null) return (<span>-</span>)
          return (
            <span>{(Number(ele_price) || 0).toFixed(4)}</span>
          )
        }
      },
      {
        align: 'center',
        title: '购电量(度)',
        minWidth: 100,
        render: (h, p) => {
          const { amount, charge_pool_amount } = p.row
          const result = (Number(amount) + Number(charge_pool_amount)).toFixed(2)
          return (<span>{result}</span>)
        }
      },
      //   {
      //     align: 'center',
      //     title: '公摊扣减(度)',
      //     minWidth: 100,
      //     key: 'charge_pool_amount'
      //   },
      //   {
      //     align: 'center',
      //     title: '电表入电(度)',
      //     minWidth: 100,
      //     key: 'amount'
      //   },
      // {
      //     align: 'center',
      //     title: '充值电量（度）',
      //     minWidth: 120,
      //     key: 'amount',
      //     render(createElement, obj) {
      //         return createElement(
      //             'span', // 标签名称
      //             (Number(obj.row.amount) + Number(obj.row.charge_pool_amount)).toFixed(2)
      //             // (+obj.row.amount).toFixed(2)
      //         );
      //     }
      // },
      {
        align: 'center',
        title: '状态',
        minWidth: 100,
        // key: 'charge_status',
        render (createElement, obj) {
          let chargrMap = ['未知', '充值中', '充值失败', '充值成功']
          return createElement(
            'span', // 标签名称
            chargrMap[+obj.row.charge_status]
          )
        }
      }
    ]

    return {
      allRoomElec: '', // 房间用电
      pubRoomElec: '', // 公摊用电
      showSum: false,
      isLoadig: true,
      isRefreshElemeterData: false, // 轮询用电记录
      size: 20,
      total: 0,
      currentPage: 1,
      columns: [columns1, columns2, columns3],
      baseColumns: [
        {
          title: '时间',
          align: 'center',
          render: (h, params) => {
            const { date } = params.row
            const baseStr = 'YYYY-MM-DD'
            const formatRule = baseStr + (this.type === 'day' ? '' : ' HH:mm')
            return <span>{dayjs(date).format(formatRule)}</span>
          }
        },
        {
          title: '房间用电量(度)',
          align: 'center',
          key: 'room_consume'
        }
      ],
      poolColumn: {
        align: 'center',
        title: '公摊用电量(度)',
        key: 'pool_consume'
      },
      leftColumn: {
        align: 'center',
        title: '剩余电量(度)',
        key: 'left_amount'
      },
      roomInfo: {},
      isPublicRoom: false,
      datas: [],
      type: 'day',
      rechargeType: 0,
      time: 0,
      timeRange: [new Date(timeBefore3), new Date(now)],
      list1: [
        {
          type: 'hour',
          name: '按小时展示'
        },
        {
          type: 'day',
          name: '按天展示'
        }
      ],
      list2: [
        {
          time: 0,
          name: '最近三天'
        },
        {
          time: 1,
          name: '最近七天'
        },
        {
          time: 2,
          name: '最近一个月'
        },
        {
          time: 3,
          name: '自定义'
        }
      ],
      list3: [
        {
          recharge: 0,
          name: '充值渠道'
        },
        {
          recharge: 1,
          name: '人工充值'
        },
        {
          recharge: 2,
          name: '微信'
        },
        {
          recharge: 3,
          name: '支付宝'
        },
        {
          recharge: 4,
          name: '接口充值'
        }
      ],
      pool_area_type: '',
      refreshTimes: 0,
      lastElemeterDataLength: Infinity
    }
  },
  created () {
    this.getRoomInfo(this.roomId)
  },
  methods: {
    /**
        * 构造房间用电配置表单
        */
    setElemeterColumn () {
      const columns = []
      if (!this.shouldNotShowPool) columns.push(this.poolColumn)
      if (this.isPayFirst) columns.push(this.leftColumn)
      return this.$set(this.columns, '0', [ ...this.baseColumns, ...columns ])
    },

    getRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.roomInfo = res
          this.getData() // 获取第一页全部数据
        }
      })
    },
    getData (page = 1, isFromTimeSelect) {
      if (page === 1) {
        this.currentPage = 1
      }
      let roomId = this.roomId
      let params = {
        limit: this.size,
        offset: this.size * (page - 1)
      }
      let startTime = new Date(this.timeRange[0]).getTime()
      let endTime = new Date(this.timeRange[1]).getTime()

      const _Now = Date().valueOf()

      // 选择时间段 3天/7天/1个月 查询
      if (isFromTimeSelect) {
        switch (this.time) {
          case 0:
            startTime = timeBefore3
            endTime = _Now
            break
          case 1:
            startTime = timeBefore7
            endTime = _Now
            break
          case 2:
            startTime = timeBefore30
            endTime = _Now
            break
        }
      }

      endTime = dayjs(endTime).endOf('day').valueOf() // 最终传给后端的end_time时间 23:59:59
      this.timeRange = [new Date(startTime), new Date(endTime)]

      let apiPath
      switch (this.recordType) {
        case 0:
          // 用电
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          // this.roomInfo.id === this.roomInfo.parent_id ? api.room_pool_electric_record : api.room_electric_record;
          apiPath = api.room_electric_record
          break
        case 1:
          // 用水
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          apiPath = api.room_water_record
          break
        case 2:
          // 充值
          if (this.rechargeType) {
            params.type = this.rechargeType
          }
          params.startTime = startTime
          params.endTime = endTime
          apiPath = api.room_charge_list
          break
      }
      util.log('startTime', new Date(params.start_time).Format('yyyy-MM-DD HH:mm'))
      util.log('endTime', new Date(params.end_time).Format('yyyy-MM-DD HH:mm'))
      http.request(this, apiPath, [roomId], params, res => {
        if (res) {
          switch (this.recordType) {
            case 0:
              this.setElemeterColumn() // 根据房间状态和公摊构造表单数据

              // 返回的是一个对象，转化为数组
              const { data, num } = this.transferData(res.data ? res.data : res)

              this.datas = data
              this.total = num
              // this.sumElec(transferedData.result); // 拿获取的数据计算用电量总数

              break
            case 1:
              const { result, total } = this.transferWaterData(res)
              this.datas = result
              this.total = total
              break
            case 2:
              // 充值
              this.datas = res.rows
              this.total = res.count || 0
              break
          }
        }
        this.isLoadig = false
      })
    },

    /**
         * 转换水表记录数据
         * @param {Object} data 用水记录数据
         * @return { Object } 数据总数 total 数据数组 result
         */
    transferWaterData (data) {
      let result = []

      for (let key in data) {
        let obj = {}
        let item = data[key]

        obj.time = key
        obj.hot_records = item.hot_amount
        obj.cold_records = item.cold_amount

        result.push(obj)
      }

      result.reverse()
      return { result, total: result.length }
    },

    /**
         * 转换电表记录数据
         * @param {Object} recordDatas 用电记录数据
         * @return { Object } 数据总数 total 数据数组 result
         */
    transferData (recordDatas) {
      const [data, num] = Object.keys(recordDatas).sort().reverse().reduce(([ result, total ], date) => {
        const { room_consume, pool_consume, left_amount } = recordDatas[date]
        result.push({
          date: Number(date),
          room_consume: isNumber(room_consume) ? room_consume : '-',
          pool_consume: isNumber(pool_consume) ? pool_consume : '-',
          left_amount: isNumber(left_amount) ? left_amount : '-'
        })
        total++
        return [ result, total ]
      }, [ [], 0 ])

      return {
        data,
        num
      }
    },

    getCurrentElemeter () {
      if (this.isLoadig) {
        return
      }
      //  获取最新电量
      let roomId = this.roomInfo.id
      http.request(this, api.room_elemeter_read, [roomId], null, res => {
        if (res) {
          this.$Message.success('抄表指令已发送,请稍后..')
          setTimeout(() => {
            this.type = 'hour'
            this.getData()
          }, 5000)
        }
      })
    },

    /**
         * 执行房间抄表操作并且切换为按小时展示
         */
    getCurrentWatermeter () {
      if (this.isLoadig) {
        return
      }
      //  获取最新水量
      let roomId = this.roomInfo.id

      http.request(this, api.room_watermeter_action_read, [roomId], null, (res, err) => {
        if (err) return

        this.$Message.info('抄表指令已发送，请稍后...')

        setTimeout(() => {
          this.type = 'hour'
          this.getData()
        }, 5000)
      })
    },

    exportTable () {
      let roomId = this.roomInfo.id
      let export_api
      let params = {}
      let startTime = new Date(this.timeRange[0]).getTime()
      let endTime = new Date(this.timeRange[1]).getTime()

      switch (this.recordType) {
        case 0:
          // 用电
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          params.download = true
          export_api = api.room_electric_record
          break
        case 1:
          // 用水
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          params.download = true
          export_api = api.room_water_record_export
          break
        case 2:
          // 充值
          if (this.rechargeType) {
            params.type = this.rechargeType
          }
          params.startTime = startTime
          params.endTime = endTime
          export_api = api.room_charge_list_export
          break
      }
      // 导出报表
      // console.log(params);
      // console.log(`params:${params},roomId:${roomId}`);
      http.exportTable(this, export_api, [roomId], params)
    }
  }
}
</script>

<style lang="less" scoped>
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
.ivu-card-body {
    min-height: 550px;
}
.ivu-table-wrapper {
    padding: 15px;
}
</style>